package com.zjhn.ds.common;

import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
import lombok.Builder;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

/**
 * 通用分页返回信息
 * @param <T>
 */
@Data
@Builder
public class PageResult<T> {

    @JsonProperty("current")
    @ApiModelProperty(value = "当前页")
    private Long current;

    @JsonProperty("size")
    @ApiModelProperty(value = "页大小")
    private Long size;

    @JsonProperty("total")
    @ApiModelProperty(value = "总数")
    private Long total;

    @JsonProperty("pages")
    @ApiModelProperty(value = "总页数")
    private Long pages;

    @JsonProperty("record")
    @ApiModelProperty(value = "数据")
    private List<T> record;

    /**
     * 分页方法
     * @param currentPage
     * @param pageSize
     * @param list
     */
    public static<T> PageResult<T> page(Long currentPage, Long pageSize, List<T> list) {
        long size = list.size();
        if (size == 0)
            return PageResult.<T>builder()
                    .current(currentPage)
                    .size(0L)
                    .total(0L)
                    .pages(pageSize)
                    .record(new ArrayList<>())
                    .build();

        if(pageSize > size){
            pageSize = size;
        }

        //求出最大页数，防止currentPage越界
        long maxPage = size % pageSize == 0 ? size / pageSize : size / pageSize + 1;

        if(currentPage > maxPage){
//            currentPage = maxPage;
            return PageResult.<T>builder()
                    .current(currentPage)
                    .size(pageSize)
                    .total((long) list.size())
                    .pages(maxPage)
                    .record(new ArrayList<>())
                    .build();
        }

        //当前页第一条数据下标
        long curIds = currentPage > 1 ? (currentPage -1) * pageSize : 0;

        List<T> pageList = new ArrayList<>();

        //将当前页的数据放进pageList
        for (int i = 0; i < pageSize && curIds + i < size; i++) {
            pageList.add(list.get(Long.valueOf(curIds + i).intValue()));
        }

        return PageResult.<T>builder()
                .current(currentPage)
                .size(pageSize)
                .total((long) list.size())
                .pages(maxPage)
                .record(pageList)
                .build();
    }
}
